package com.example.tijianserver.controller;


import cn.hutool.core.lang.Snowflake;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.tijianserver.config.AliPayConfig;
import com.example.tijianserver.dto.OrdersDTO;
import com.example.tijianserver.dto.OrserSPayStasteDTO;
import com.example.tijianserver.pojo.Orders;
import com.example.tijianserver.service.OrdersService;

import com.example.tijianserver.utils.DateFormatExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private AliPayConfig aliPayConfig;

    @RequestMapping("alipay")
    public String alipay(@RequestBody OrdersDTO ordersDTO) throws IOException, AlipayApiException, ParseException {

//        生产订单号
        Snowflake snowflake = new Snowflake();
        long id=snowflake.nextId()%1000000000;
        ordersDTO.setOrderId((int) id);

        //将时间格式CST转换为GMT
        Date date = DateFormatExample.getDate(ordersDTO.getSelectDay());

        Orders orders = new Orders();

        orders.setOrderId(ordersDTO.getOrderId());
        orders.setOrderDate(date);
        orders.setUserId(ordersDTO.getUserId());
        orders.setHpId(ordersDTO.getHospital().getHpId());
        orders.setSmId(ordersDTO.getSetmeal().getSmId());
        orders.setState(1);

        ordersService.insert(orders);

        // 实例化客户端,填入所需参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 在公共参数中设置回跳和通知地址
        request.setReturnUrl(aliPayConfig.getRETURN_URL());
        request.setNotifyUrl(aliPayConfig.getNOTIFY_URL());

        // 商户订单号，商户网站订单系统中唯一订单号，必填

        String out_trade_no = String.valueOf(ordersDTO.getOrderId());
        // 付款金额，必填
        String  total_amount = String.valueOf(ordersDTO.getSetmeal().getPrice());
        // 订单名称，必填
        String subject = ordersDTO.getSetmeal().getName();

        request.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        return form;
    }


    @RequestMapping("/returnUrl")
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();

        Map<String, String[]> requestParams = request.getParameterMap();

        for (String name : requestParams.keySet()) {
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr +
                        values[i] + ",";
            }

            // 解决乱码
            valueStr = new String(valueStr.getBytes(StandardCharsets.UTF_8),
                    StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }

        System.out.println(params);// 查看参数都有哪些

        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                aliPayConfig.getALIPAY_PUBLIC_KEY(), aliPayConfig.getCHARSET(),
                aliPayConfig.getSIGN_TYPE()); // 调用SDK验证签名

        System.out.println(signVerified);
        // 验证签名
        if(signVerified){
            System.out.println("---------");
            // 商户订单号
            String out_trade_no = new
                    String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

//            // 支付宝交易号
//            String trade_no = new
//                    String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

            // 付款金额
            String total_amount = new
                    String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

            System.out.println("商户订单号 = " + out_trade_no);
            System.out.println("付款金额 = " + total_amount);

//             支付成功，修改支付状态, 状态码：1=>2

            int orderId=Integer.valueOf(out_trade_no);

            ordersService.updatestate(orderId,2);


            System.out.println("Redirecting to success page...");


            response.sendRedirect("http://localhost:5174/appointmentsuccess");
        }else{
            response.sendRedirect("http://localhost:5173/appointmentfalse");
            System.out.println("Redirecting to fffff page...");
        }
    }
}






